package com.example.demo.controller;

import java.io.File;
import java.io.IOException;
import java.io.Writer;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import com.google.gson.Gson;

/// <summary>
/// 涓婁紶鏂囦欢 杩斿洖鏁版嵁妯″瀷
/// </summary>
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.RequestParam;
 
 

@Controller
@RequestMapping("/goods")
public class UploadFileDTO {
 
    private Logger logger = Logger.getLogger(UploadFileDTO.class);

 

    @RequestMapping("/upload")
    public void upload(HttpServletResponse response,HttpServletRequest request, @RequestParam(value = "file", required = false) MultipartFile file) throws IOException {
        System.out.println("执行upload");
        request.setCharacterEncoding("UTF-8");
        logger.info("执行图片上传");
        String user = request.getParameter("user");
        logger.info("user:"+user);
       String trueFileName="";
        String path1 = System.getProperty("user.dir");//项目根目录
        File file2 = new File(path1);
        String parent = file2.getParent();//项目所在目录
        if(!file.isEmpty()) {
            logger.info("成功获取照片");
            String fileName = file.getOriginalFilename();
            String path = null;
            String type = null;
            type = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()) : null;
            logger.info("图片初始名称为：" + fileName + " 类型为：" + type);
            if (type != null) {
                    // 项目在容器中实际发布运行的根路径
                    String realPath = request.getSession().getServletContext().getRealPath("/");
                    // 自定义的文件名称
                    trueFileName = String.valueOf(System.currentTimeMillis()) + fileName;
                    // 设置存放图片文件的路径
                    path = path1+"\\src\\main\\resources\\static\\images\\" + trueFileName;
                    logger.info("存放图片文件的路径:" + path);
                    file.transferTo(new File(path));
                    logger.info("文件成功上传到指定目录下");

            }else {
                logger.info("文件类型为空");
               
            }
        }else {
            logger.info("没有找到相对应的文件");
          
        }
        Gson gson = new Gson();
		String json = gson.toJson(trueFileName);
		response.setHeader("Access-Control-Allow-Origin", "*");
		/* 閺勭喎褰跨悰銊с仛閹碉拷閺堝娈戝鍌氱厵鐠囬攱鐪伴柈钘夊讲娴犮儲甯撮崣妤嬬礉 */
		response.setHeader("Access-Control-Allow-Methods", "GET,POST");
		response.setContentType("text/json,charset=utf-8");
		response.setCharacterEncoding("utf-8");
		Writer out = response.getWriter();
		out.write(json);
		out.flush();
      
    }
    


}